﻿using CNative.WebApi.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web;

namespace CNative.WebApi.Utils
{
    /// <summary>
    /// 字段属性验证工具类
    /// </summary>
    public class ValidatePropertyUtil
    {
        /// <summary>
        /// 验证数据 
        /// true:验证通过 false 验证不通过
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="errMsg">错误信息</param>
        public static bool Validate(object data, out string errMsg)
        {
            PropertyInfo[] propertyInfoList = data.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false).Length > 0)
                {
                    object value = propertyInfo.GetValue(data);
                    if (value == null)
                    {
                        errMsg = "属性 " + propertyInfo.Name + " 必填";
                        return false;
                    }
                }

                object[] attrArr = propertyInfo.GetCustomAttributes(typeof(DateTimeAttribute), false);
                if (attrArr.Length > 0)
                {
                    DateTimeAttribute attr = attrArr[0] as DateTimeAttribute;
                    object value = propertyInfo.GetValue(data);
                    if (value == null)
                    {
                        errMsg = "属性 " + propertyInfo.Name + " 是日期时间格式，格式：" + attr.Format;
                        return false;
                    }
                    else
                    {
                        DateTime dt;
                        if (!DateTime.TryParseExact(value.ToString(), attr.Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                        {
                            errMsg = "属性 " + propertyInfo.Name + " 是日期时间格式，格式：" + attr.Format;
                            return false;
                        }
                    }
                }
            }

            errMsg = null;
            return true;
        }
    }
}